package org.dynasty.dynamic.scanner;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.ds.ItemDataSource;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.Configuration;
import org.dynasty.memory.compiler.DynamicCompiler;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.*;

/**
 * framework
 *
 * @author: dynasty
 * @create: 2021-08-02 23:32
 */
@Slf4j
@Component
public class MemoryClassGenerator implements ApplicationRunner {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (dataSource instanceof DynamicRoutingDataSource) {
            DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
            Map<String, DataSource> currentDataSources = dynamicRoutingDataSource.getCurrentDataSources();
            for (String currentDataSourceKey : currentDataSources.keySet()) {
                mybatisGenerator(currentDataSourceKey, currentDataSources.get(currentDataSourceKey));
                generateMapper(currentDataSourceKey);
            }

        } else {

        }
        // TODO 单数据库

    }

    private void generateMapper(String dataSource) throws ClassNotFoundException {
        Map<String, byte[]> sourceCodeMap = CompileContext.SOURCE_CODE_MAP;

        DynamicCompiler dynamicCompiler = new DynamicCompiler(MemoryClassGenerator.class.getClassLoader());
        // 以字节数组方式动态载入class
        for (String qualifiedClassName : sourceCodeMap.keySet()) {
//            String canonicalClassName = determineCanonicalClassName(qualifiedClassName);
            dynamicCompiler.addSource(qualifiedClassName, new String(sourceCodeMap.get(qualifiedClassName)));
        }

        // 获得编译好的字节码
        // k -> className
        // v -> bytecode
        Map<String, Class<?>> classMap = dynamicCompiler.build();
        for (String className : classMap.keySet()) {
            Class<?> clazz = Class.forName(className, true, dynamicCompiler.getClassLoader());
            if (className.endsWith("Mapper")) {
                CompileContext.MAPPER_CLASS_MAP.put(className, (Class<? extends CustomizedBaseMapper>) clazz);
            } else {
                Context.ENTITY_CLASS_MAP.put(dataSource + "." + className.replaceFirst("org\\.dynasty\\.dynamic\\.scanner\\.\\w+\\.", ""), clazz);
            }
        }

        // 注册mapper
        int count = 0;
        for (String mapperClassName : CompileContext.MAPPER_CLASS_MAP.keySet()) {
            Class<? extends CustomizedBaseMapper> mapperClass = CompileContext.MAPPER_CLASS_MAP.get(mapperClassName);

            Class<?>[] interfaces = mapperClass.getInterfaces();
            boolean isBaseMapperClass = false;
            for (Class<?> anInterface : interfaces) {
                if (anInterface.equals(CustomizedBaseMapper.class)) {
                    isBaseMapperClass = true;
                }
            }

            if (isBaseMapperClass) {
                // register mapper bean
                Configuration configuration = sqlSessionTemplate.getConfiguration();
                configuration.getMapperRegistry().addMapper(mapperClass);

                BaseMapper mapper = configuration.getMapper(mapperClass, sqlSessionTemplate);
                log.info("注册{}MapperBean成功", mapperClassName);
                Context.ONE_MAPPER_MAP.putIfAbsent(dataSource, (CustomizedBaseMapper) mapper);
                Context.MAPPER_MAP.put(dataSource + "." + mapperClassName.replaceFirst("org\\.dynasty\\.dynamic\\.scanner\\.\\w+\\.", ""), (CustomizedBaseMapper) mapper);
                count++;
            }
        }

        log.info("数据源 {} mapper自动扫描注册完毕，共加载 {} 个mapper bean", dataSource, count);

        // clear memory
        CompileContext.clear();
    }

    private void mybatisGenerator(String currentDataSourceKey, DataSource dataSource) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
//        String projectPath = System.getProperty("user.dir");
        String projectPath = System.getProperty("user.dir");
        String module = "entity-mapper-scanner";
        gc.setOutputDir(projectPath + "/" + module + "/src/main/java");
        gc.setAuthor("dynasty");
        gc.setOpen(false);
        gc.setIdType(IdType.INPUT);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();

        setDataSourceProperties(dataSource, dsc);

        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("dynamic.scanner");
        pc.setParent("org.dynasty");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "mapper.java.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录，自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在，不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(false);
        strategy.setRestControllerStyle(true);
        // 公共父类
        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
//        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
//        strategy.setInclude(".+");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        // 自定义引擎
        mpg.setTemplateEngine(new FreemarkerOutput2MemoryTemplateEngine());
        mpg.execute();

        for (TableInfo tableInfo : mpg.getConfig().getTableInfoList()) {
            Context.TABLEINFO_MAP.put(currentDataSourceKey + "." + tableInfo.getName(), tableInfo);
        }
    }

    private void setDataSourceProperties(DataSource dataSource, DataSourceConfig dsc) {
        String url = null;
        String driverName = null;
        String username = null;
        String password = null;

        if (dataSource instanceof ItemDataSource) {
            DataSource realDataSource = ((ItemDataSource) dataSource).getRealDataSource();
//            if (realDataSource instanceof HikariDataSource) {
//                HikariDataSource hikariDataSource = (HikariDataSource) realDataSource;
//                url = hikariDataSource.getJdbcUrl();
//                driverName = hikariDataSource.getDriverClassName();
//                username = hikariDataSource.getUsername();
//                password = hikariDataSource.getPassword();
//            }
            if (realDataSource instanceof DruidDataSource) {
                DruidDataSource druidDataSource = (DruidDataSource) realDataSource;
                url = druidDataSource.getUrl();
                driverName = druidDataSource.getDriverClassName();
                username = druidDataSource.getUsername();
                password = druidDataSource.getPassword();
            }
        }

//        dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dsc.setUrl(url);
//        dsc.setSchemaName("public");
        dsc.setDriverName(driverName);
        dsc.setUsername(username);
        dsc.setPassword(password);
    }

}
